<template>
  <el-dropdown class="dropdown" placement="bottom-end" @command="changeLang" trigger="click">
    <SvgIcon icon-class="language" class-name="icon"></SvgIcon>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item
          v-for="item in LangList"
          :key="item.code"
          :command="item.code"
          :disabled="item.code === lang"
        >
          {{ item.name }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script lang="ts">
import type { ILang } from "@/store/modules/appSetting";

import { defineComponent, computed } from "vue";
import appStore from "@/store";

export default defineComponent({
  name: "LangToggle",
  props: {
    fontSize: {
      // 实际上是number类型, 不带单位简写才是string类型
      type: [String, Number],
      default: "30",
      validator: (value: string | number) => {
        if (
          (typeof value === "string" &&
            /^\d+(px)?$/.test(value) &&
            parseInt(value) >= 0) ||
          (typeof value === "number" && value >= 0)
        ) {
          return true;
        }
        return false;
      },
    },
  },

  setup(props, ctx) {
    // 对传入的props的fontSize进行简单的进一步处理
    const fontSize = computed(() => {
      let size = props.fontSize;
      if (typeof size === "string" && ~size.indexOf("px")) {
        return size;
      }
      return size + "px";
    });

    // 语言列表
    const LangList = [
      { name: "中文", code: "zh-CN" },
      { name: "English", code: "en-US" },
    ];
    // 获取当前语言
    const lang = computed(() => appStore.appSetting.lang);
    // window.document.documentElement.setAttribute("lang", lang.value);

    // 切换语言
    const changeLang = (e: ILang) => {
      appStore.appSetting.setLang(e);
    };

    return {
      fontSize,
      LangList,
      changeLang,
      lang,
    };
  },
});
</script>

<style lang="scss" scoped>
.dropdown {
  &:focus-visible {
    outline: none;
  }
  .icon {
    // color: $black_3b3b3b;
    // @include font_color("font_color");
    font-size: v-bind("fontSize");
    cursor: pointer;
    &:focus {
      outline: none;
    }
  }
}
</style>
